package cn.com.flower.passport.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.io.Serializable;

@Configuration
public class RedisConfiguration {

    @Autowired
    RedisConnectionFactory redisConnectionFactory;

    // 在需要时调用
    @Bean
    public RedisTemplate<String, Serializable> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        // 创建一个 RedisTemplate 实例，用于操作 Redis 数据 String为Key Serializable为Value
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        // 连接redis
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 用于将key序列化为字符串
        redisTemplate.setKeySerializer(RedisSerializer.string());
        // 用于将值序列化为 JSON 格式
        redisTemplate.setValueSerializer(RedisSerializer.json());
        // 设置 Hash 的 Key 和 Value 序列化方式
        redisTemplate.setHashKeySerializer(RedisSerializer.string());
        redisTemplate.setHashValueSerializer(RedisSerializer.json());
        // 返回配置好的 RedisTemplate 实例

        return redisTemplate;
    }
}
